<script setup>
import { ref, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

import { getFieldsApi, getSourceApi, saveSourceApi } from '@/service/db.js'
let selectedFields = []
const drawerTitle = ref('设置数据源')

const fieldList = ref([])
const ruleForm = ref({
  table: '',
  title: '',
  model: '',
  fields: []
});

// Add table reference
const fieldTableRef = ref(null);
const rules = ref({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  model: [
    { required: true, message: '请输入模型', trigger: 'blur' }
  ]
});



// 获取数据源配置
const getSourceConfig = (table) => {
  getSourceApi({ table }).then(({ code, data }) => {
    if (code === 200) {
      ruleForm.value.fields = data.fields
      // fieldTableRef 设置选中， element-plus 的 table 组件没有 setSelection 方法
      nextTick(() => {
        if (Array.isArray(data.fields)) {
          fieldList.value.forEach(row => {
            if (data.fields.includes(row.Field)) {
              fieldTableRef.value.toggleRowSelection(row, true);
            }
          });
        }
      });
    }
  })
}

// 获取表的字段
const getFields = (table) => {
  getFieldsApi({ table }).then(res => {
    fieldList.value = res.data
    // 调用配置
    getSourceConfig(table)
  })
}

const emit = defineEmits(['fetch-list'])

const ruleFormRef = ref(null);
const submitForm = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      let data = {};
      data.table = table.value;
      data.title = ruleForm.value.title;
      data.fields = selectedFields;
      saveSourceApi(data).then(res => {
        if (res.code === 200) {
          ElMessage({
            message: '提交成功',
            type: 'success'
          });
          closeDrawer();
          emit('fetch-list')
        } else {
          ElMessage({
            message: '提交失败',
            type: 'error'
          });
        }
      });
    } else {
      ElMessage({
        message: '提交失败',
        type: 'error'
      });
      return false;
    }
  });
}

const resetForm = () => {
  ruleFormRef.value.resetFields();
  // 重置选中
  selectedFields = []
  fieldTableRef.value.clearSelection()
}

const table = ref('')
const dialogVisible = ref(false)
const openDrawer = (row) => {
  table.value = row.name;
  drawerTitle.value = `设置数据源 - ${table.value}`
  dialogVisible.value = true;

  getFields(table.value)

  // 重置表单
  ruleForm.value = {
    table: table.value,
    title: '',
    model: '',
    fields: []
  }
}
const closeDrawer = () => {
  dialogVisible.value = false;
}

// 选择字段
const handleSelectionChange = (val) => {
  // 便利选中的字段中的Field，并存入selectedFields
  selectedFields = val.map(item => item.Field)
}

defineExpose({
  openDrawer,
  closeDrawer
});

</script>

<template>
  <el-drawer :title="drawerTitle" v-model="dialogVisible" size="100%">
    <div class="container">
      <div class="form">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" :inline="true" label-position="left">
          <el-form-item label="标题" prop="title">
            <el-input v-model="ruleForm.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleFormRef')">保存</el-button>
            <el-button @click="resetForm('ruleFormRef')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="field-list">
        <el-table ref="fieldTableRef" :data="fieldList" border @selection-change="handleSelectionChange"
          row-key="Field">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="Field" label="字段"></el-table-column>
          <el-table-column prop="Type" label="类型"></el-table-column>
          <el-table-column prop="Comment" label="描述"></el-table-column>
        </el-table>
      </div>

    </div>
  </el-drawer>
</template>

<style scoped lang="less">
.flex {
  display: flex;
  justify-content: space-between;

  .btn {
    cursor: pointer;
  }
}

.flex.tip {
  color: #409eff;
  font-weight: bold;
}

.container {}
</style>
